# Replication archive for: Coppock, Alexander and Seth J. Hill and Lynn Vavreck. 2020. "The Small Effects of Political Advertising are Small Regardless of Context, Message, Sender, or Receiver: Evidence from 59 Real-time Randomized Experiments" Science Advances, forthcoming.

# this function "tidies" the output of an rmeta::meta.summaries object
tidy.meta.summaries <-
  function(fit){
    data.frame(
      estimate = fit$summary,
      std.error = fit$se.summary,
      conf.low = summary(fit)$summci[1],
      conf.high = summary(fit)$summci[3]
    )
  }

glance.meta.summaries <-
  function(fit){
    data.frame(
      p.value = fit$het[3],
      tau2 = fit$tau2,
      tau = sqrt(fit$tau2)
    )
  }



# this function operates on a data.frame of estimates and returns the random effects estimate
# if the dataset only has one row, then it returns the point estimate
random_effects_estimator <- 
  function(data) {
    if (nrow(data) == 1) {
      return(data[, c("estimate", "std.error", "conf.high", "conf.low")])
    } else {
      meta_out <-
        with(data, meta.summaries(estimate, std.error, method = "random"))
      return(tidy(meta_out))
    }
  }


# this function estimates the effect of treatment on a dv, controlling for pre-treatment covs
# it returns a tidy data.frame
estimate_ad_effects <-
  function(data, dv) {
    formula <- formula(paste0(dv, "~ ad_id_fac + pid_7_pre + ideo5_pre + female_pre"))
    
    data %>%
      filter(!is.na(!!sym(dv))) %>%
      group_by(date) %>%
      do(tidy(lm_robust(formula, weights = weights, data = .)))
  }






add_parens <- function(x, digits = 3) {
  x <- as.numeric(x)
  return(paste0("(", sprintf(paste0("%.", digits, "f"), x), ")"))
}

format_num <- function(x, digits = 3) {
  x <- as.numeric(x)
  return(paste0(sprintf(paste0("%.", digits, "f"), x)))
}

make_se_entry <- function(est, se, digits = 2){
  paste0(format_num(est, digits = digits)," ", add_parens(se, digits = digits))
}

make_interval_entry <-
  function(conf.low, conf.high, digits = 2) {
    paste0(
      "[",
      format_num(conf.low, digits = digits),
      ", ",
      format_num(conf.high, digits = digits),
      "]"
    )
  }


texprep <- function(fitlist, stat = "estimate") {
  # estimate     se  zval   pval   ci.lb   ci.ub
  fitlist %>%
    map(summary) %>%
    map(coef) %>%
    map(as_tibble) %>%
    map(pull, stat)
}

